﻿Imports System.IO
Imports System.Text
Imports Microsoft
Imports System.Data.SqlClient
Imports System.Data.Sql
Imports DataObject
Imports Microsoft.ApplicationBlocks.Data
Imports Microsoft.SqlServer.Management.Smo
Imports BusinessObject

Public Class frmDangNhap

    Dim sNameServer As String = ""
    Dim sUserName As String = ""
    Dim sPassword As String = ""
    Dim oTable As New Data.DataTable
    Dim oConnect As New SqlConnection
    Dim oSqlCmd As New SqlCommand
    Dim oSqlDa As New SqlDataAdapter
    Dim oNguoiDung As New BusNguoiDung
    Dim ptyNguoiDung As New NguoiDung

    Private Sub LoadSettingsFrom(ByVal sFileName As String)
        Dim oDataset As New DataSet
        If Not My.Computer.FileSystem.FileExists(sFileName) Then
            Exit Sub
        End If
        If (My.Computer.FileSystem.FileExists(sFileName)) Then
            oDataset.ReadXml(sFileName)
            Dim oDatatable As DataTable
            oDatatable = oDataset.Tables("FileConfig")
            oDatatable = oDataset.Tables(0)
            If oDatatable.Rows.Count > 0 Then
                cboServer.Text = oDatatable.Rows(0)("Server")
                txtUsername.Text = oDatatable.Rows(0)("UserName")
                cboDatabase.Text = oDatatable.Rows(0)("Database")
            Else
                cboServer.Text = ""
                txtUsername.Text = ""
                txtPassword.Text = ""
                cboDatabase.Text = ""
            End If
        End If
    End Sub

    Private Sub GetServerList()
        'Load dữ liệu cho combobox cboServer : Tìm các server tồn tại trong máy
        With cboServer
            .Items.Clear()
        End With
        oTable = SmoApplication.EnumAvailableSqlServers(False)
        For Each oRow As Data.DataRow In oTable.Rows
            sNameServer = oRow("Server").ToString
            If (Not Convert.IsDBNull(oRow("Instance")) And oRow("Instance").ToString().Length > 0) Then
                sNameServer += "\" & oRow("Instance").ToString()
            ElseIf cboServer.Items.IndexOf(sNameServer) < 0 Then
                cboServer.Items.Add(sNameServer)
            ElseIf cboServer.Items.Count > 0 Then
                cboServer.SelectedIndex = 0
            End If
        Next
    End Sub

    Private Sub GetDatabaseList()
        Try
            With cboDatabase
                .Items.Clear()
            End With
            cboDatabase.Items.Clear()
            Dim oDataReader As SqlClient.SqlDataReader

            Dim conn As New SqlClient.SqlConnection
            Dim cmd As New SqlClient.SqlCommand
            'Persist Security Info=True
            conn = New SqlClient.SqlConnection("Data source = " & cboServer.Text & "; Initial Catalog = Master; Persist Security Info=True; User = sa;Password = thangphuong")
            conn.Open()
            cmd = New SqlClient.SqlCommand("SELECT * FROM sys.Databases", conn)
            oDataReader = cmd.ExecuteReader()
            While oDataReader.Read()
                cboDatabase.Items.Add(oDataReader(0))
            End While
        Catch ex As Exception
        End Try
    End Sub

    Private Sub SaveSettingsAs(ByVal sFileName As String)

        Dim oTable As New DataTable
        Dim oDataset As New DataSet

        'Lưu setting database, server etc
        oTable.Columns.Add("Server", "".GetType)
        oTable.Columns.Add("Database", "".GetType)
        oTable.Columns.Add("UserName", "".GetType)
        oTable.Rows.Add(New Object() {cboServer.Text, cboDatabase.Text, txtUsername.Text})

        oTable.TableName = "DefaultValues"
        oDataset.Tables.Add(oTable)

        Dim oDTPresetNew As New DataTable
        oDTPresetNew.TableName = "Preset"
        oDTPresetNew.Columns.Add("Server", "".GetType())
        oDTPresetNew.Columns.Add("Database", "".GetType())
        oDTPresetNew.Columns.Add("UserName", "".GetType())

        Dim DTPreset As DataTable
        Dim DSPreset As New DataSet

        'Kiểm tra sự tồn tại của file
        If (My.Computer.FileSystem.FileExists(sFileName)) Then
            DSPreset.ReadXml(sFileName)
            DTPreset = DSPreset.Tables("FileConfig")
        End If

        If (Not IsNothing(DTPreset)) Then
            oDTPresetNew = DTPreset.Copy()
        End If

        Dim i As Integer
        Dim bFound As Boolean = False
        For i = 0 To oDTPresetNew.Rows.Count - 1
            If oDTPresetNew.Rows(i)("Server").ToString().ToUpper() = cboServer.Text.ToUpper() Then
                bFound = True
                oDTPresetNew.Rows(i)("Database") = cboDatabase.Text
                oDTPresetNew.Rows(i)("UserName") = txtUsername.Text
            End If
        Next

        If (Not bFound) Then
            If (cboServer.Text.Trim() <> "") Then
                oDTPresetNew.Rows.Add(New Object() {cboServer.Text, cboDatabase.Text, txtUsername.Text})
            End If
        End If
        oDataset.Tables.Add(oDTPresetNew)
        oDataset.WriteXml(sFileName)
        oDataset.Tables.Clear()
    End Sub

    Private Sub LoadStatus()
        FrmMain.tbrFooter.Panels("mnuFooter_Username").Text = "Tên đăng nhập : " & txtUsername.Text
        FrmMain.tbrFooter.Panels("mnuFooter_Database").Text = "CSDL : " & cboDatabase.Text
    End Sub

    Private Sub frmDangNhap_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        LoadSettingsFrom(My.Application.Info.DirectoryPath + "\DefaultValues.ConfigSettings")
        Me.btnLogin.Focus()
    End Sub

    Private Sub cboServer_BeforeDropDown(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles cboServer.BeforeDropDown
        Try
            If cboServer.Items.Count = 0 Then
                Me.Cursor = Cursors.WaitCursor
                GetServerList()
                Me.Cursor = Cursors.Default
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Sub

    Private Sub cboDatabase_BeforeDropDown(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles cboDatabase.BeforeDropDown
        Try
            Me.Cursor = Cursors.WaitCursor
            GetDatabaseList()
            Me.Cursor = Cursors.Default
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub

    Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
        Try
            If ((cboServer.Text <> "") And (cboDatabase.Text <> "")) Then
                sConn = "Data source = " & cboServer.Text & "; Initial Catalog = " & cboDatabase.Text & ";Persist Security Info=True;User ID=sa;Password=thangphuong"
            End If
            ptyNguoiDung.TenDangNhap = txtUsername.Text
            ptyNguoiDung.MatKhau = txtPassword.Text
            If (oNguoiDung.KiemTraNguoiDung(sConn, ptyNguoiDung) = True) Then
                Me.Hide()
                frmMainLogin.Hide()
                SaveSettingsAs(My.Application.Info.DirectoryPath + "\DefaultValues.ConfigSettings")
                LoadStatus()
                Me.Close()
                frmMain.ShowDialog()
            Else
                MessageBox.Show("Tên người dùng hoặc mật khẩu không chính xác", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
    End Sub

End Class